package cn.quevo.core.entity.query;

import cn.quevo.core.entity.BaseEntity;
import cn.quevo.core.lang.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
 * 查询实体
 *
 * @author July july_sky@foxmail.com
 * @date 2018-03-09 14:59:37
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @version 1.0
 * @param null
 * @return
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Query extends BaseEntity {

    /**
     * 
     */
    private static final long serialVersionUID = 8385654802124389015L;

    /** 排序字段 */
    private String sortName;
    /** 排序方式 */
    private String sortOrder;
    /** 排序字符串 */
    private String orderBy;

    public String getOrderBy() {
        if (StringUtils.isBlank(orderBy)) {
            this.orderBy = formatSort();
        }
        return orderBy;
    }

    private String formatSort() {
        if (StringUtils.isBlank(this.sortName)) {
            return null;
        }
        String orderBy = sortName.concat(" ").concat(StringUtils.isBlank(sortOrder) ? "asc" : sortOrder);
        String[] orderBys = orderBy.toString().split(",");
        StringBuffer orderByStr = new StringBuffer();
        String[] _by = null;
        for (String sort : orderBys) {
            _by = sort.split(" ");
            if (_by[0].toString().indexOf(".") == -1) {
                orderByStr.append("\"").append(_by[0].trim()).append("\"");
            } else {
                orderByStr.append(_by[0].trim());
            }
            if (_by.length <= 1 || StringUtils.isBlank(_by[1]) || "asc".equals(_by[1].trim().toLowerCase())) {
                orderByStr.append(" asc,");
            } else {
                orderByStr.append(" desc,");
            }
        }
        return orderByStr.substring(0, orderByStr.length() - 1);
    }
}
